import React, { useRef, useEffect } from 'react'
import * as echarts from 'echarts';
import { getMap } from '../../../api';
import './map.css'

function Map() {
    const map = useRef(null);
    const list = (name, adcode) => {
        getMap(adcode).then(res => {
            const mycart = echarts.init(map.current);
            console.log(res);
            echarts.registerMap(name, res.data);
            let option = {
                title: {
                    text: name,
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}<br/>{c} (p / km2)'
                },
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'right',
                    top: 'center',
                    feature: {
                        dataView: { readOnly: false },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                visualMap: {
                    min: 8,
                    max: 50,
                    text: ['High', 'Low'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['lightskyblue', 'yellow', 'orangered']
                    }
                },
                geo: {
                    map: name,
                    label: {
                        emphasis: {
                            show: false
                        }
                    }
                },
                series: [
                    {
                        type: 'effectScatter',
                        coordinateSystem: 'geo',
                        data: [
                            [116.405285, 39.904989]
                        ]
                    },
                    {
                        name: name,
                        type: 'map',
                        map: name,
                        label: {
                            show: false
                        },
                        data: res.data.features.map(item => {
                            return {
                                name: item.properties.name,
                                value: item.properties.childrenNum,
                                adcode: item.properties.adcode
                            }
                        })
                    }]
            }
            mycart.setOption(option);
            mycart.on('click', function (e) {
                console.log(e);
                let { name, adcode } = e.data;
                list(name, adcode);
            })
        }).catch(error => {
            console.log(error);
        })
    }
    useEffect(() => {
        list('中华人民共和国', 100000)
    }, [])
    return (
        <div className='map_box' ref={map}></div>
    )
}

export default Map